package fasilkom.antz.sprite;

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.Transparency;

import com.golden.gamedev.object.GameFont;
import com.golden.gamedev.object.Sprite;
import com.golden.gamedev.util.ImageUtil;


/**
 * Sprite yang berupa teks.
 *
 */
public class FontSprite extends Sprite {

	private static final long serialVersionUID = 4274094491633642381L;
	
	private String text;
	
	private GameFont font;
	
	private int lineSpacing = 0;

	private Color color = Color.BLACK;
	
	// CONSTRUCTOR //
	
	public FontSprite(String text, GameFont font) {
		this.font = font;
		setText(text);
	}
	
	public FontSprite(String text, GameFont font, int lineSpacing, Color color) {
		this(text, font);
		setLineSpacing(lineSpacing);
		setColor(color);
	}
	
	// METHOD //
	
	private void notifyTextChanged() {
		if (getWidth() <= 0 || getHeight() <= 0) {
			setImage(null);
			return;
		}
		
		setImage(ImageUtil.createImage(getWidth(), getHeight(),
				Transparency.TRANSLUCENT));
		int y = 0;
		Graphics2D g = getImage().createGraphics();
		g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.
				VALUE_ANTIALIAS_ON);
		g.setColor(getColor());
		
		for (String i : text.split("\n")) {
			font.drawString(g, i, 0, y);
			y += font.getHeight() + lineSpacing;
		}
		
		g.dispose();
	}
	
	// GETTER/SETTER //
	
	/**
	 * Set the text as multiline string.
	 * @param lines per-line texts
	 */
	public void setText(String text) {
		if (text.equals(this.text))
			return;
		
		this.text = text;
		String[] lines = text.split("\n"); 
		
		// Tinggi setiap baris ditambah space antarbaris
		height = (font.getHeight() + lineSpacing) * lines.length - lineSpacing;
		if (height < 0)
			height = 0;
		
		// Lebar baris terbesar
		width = 0;
		for (String i : lines) {
			int w = font.getWidth(i);
			if (w > width)
				width = w;
		}
		
		notifyTextChanged();
	}

	/**
	 * Return the text.
	 * @return the text
	 */
	public String getText() {
		return text;
	}

	/**
	 * Set the inter-line spacing in pixel.
	 * @param lineSpacing line spacing
	 */
	public void setLineSpacing(int lineSpacing) {
		this.lineSpacing = lineSpacing;
	}

	/**
	 * Get the inter-line spacing in pixel.
	 * @return line spacing
	 */
	public int getLineSpacing() {
		return lineSpacing;
	}

	public void setColor(Color color) {
		this.color = color;
	}

	public Color getColor() {
		return color;
	}

}
